package read

import (
	"encoding/json"
	"io/fs"
	"io/ioutil"
	"os"
	"path/filepath"
	"playbook/ginsvr/src/global"
	"playbook/ginsvr/src/orm"
	"strings"

	"strconv"

	"github.com/sirupsen/logrus"
)

var (
	jsonFileList []string
)

// type Proc struct {
// 	Name            string
// 	Overtime        string
// 	Version         string
// 	Inputparameter  []orm.Parameter
// 	Outputparameter []orm.Parameter
// 	Activities      []orm.Activity
// 	Scripts         []orm.Script
// 	Loop            []orm.Loop
// 	Processid       string
// 	Transion        []Transion
// 	Desc            string
// }

//遍历文件的回调函数
func walkFunc1(path string, info fs.FileInfo, err error) error {
	if info.IsDir() {
		return nil
	}

	if matchjson := strings.Contains(path, ".json"); matchjson {
		jsonFileList = append(jsonFileList, path)
	}

	return nil
}

//扫描json，创建组合服务信息
func Processscan() orm.Response {

	var resp orm.Response

	localPath := orm.GetLocalPath("00001")

	jsonFileList = []string{}

	err := filepath.Walk(localPath.LocalPath, walkFunc1)

	if err != nil {
		global.LOG.WithFields(logrus.Fields{
			"err": err,
		}).Error("java source search err.")
		resp.RespCode = "000001"
		resp.RespMsg = err.Error()

		return resp
	}

	pronum, subpronum := addProcessList(jsonFileList)

	global.LOG.Infof("扫描到json文件%d个,成功添加组合服务%d条，子流程%d\n", len(jsonFileList), pronum, subpronum)

	resp.RespCode = "000000"
	resp.RespMsg = "扫描到json文件" + strconv.Itoa(len(jsonFileList)) + "个,成功添加组合服务" + strconv.Itoa(pronum) +
		"条，子流程" + strconv.Itoa(subpronum) + "条"
	return resp

}

//获取原子服务、参数扫描结果列表
func addProcessList(filePaths []string) (int, int) {

	var pronum int = 0
	var subpronum int = 0

	for _, jsonpath := range jsonFileList {
		//如果是组合服务json,保存到数据库
		if ok, _, process, _ := isProcess(jsonpath); ok {
			pro := orm.AddProcess(process).(map[string]interface{})
			if pro["respCode"] == "000001" {
				global.LOG.Errorf("组合服务%s添加失败,%s\n", jsonpath, pro["respMsg"])
			} else {
				pronum++
			}
		}

		//如果是子流程json，保存到数据库
		if _, ok, _, subprocess := isProcess(jsonpath); ok {
			pro := orm.AddSubprocess(subprocess).(map[string]interface{})
			if pro["respCode"] == "000001" {
				global.LOG.Errorf("子流程%s添加失败,%s\n", jsonpath, pro["respMsg"])
			} else {
				subpronum++
			}
		}
	}
	return pronum, subpronum
}

func isProcess(filePath string) (isprocess bool, issuprocess bool, process orm.FullProcess, subprocess orm.FullSubProcess) {

	jsonFile, err := os.Open(filePath)
	if err != nil {
		global.LOG.WithFields(logrus.Fields{
			"err": err,
		}).Error("error opening json file")
		return
	}
	defer jsonFile.Close()

	//读取文件
	jsonData, err := ioutil.ReadAll(jsonFile)
	if err != nil {
		global.LOG.WithFields(logrus.Fields{
			"err": err,
		}).Error("error reading json file")
		return
	}

	var data map[string]interface{}
	err = json.Unmarshal(jsonData, &data)

	//如果是组合服务文件，添加组合服务
	if _, ok := data["process"]; ok {
		//将组合服务解析成FullProcess对象
		var proc orm.FullProcess
		err = json.Unmarshal(jsonData, &proc)
		if err != nil {
			global.LOG.WithFields(logrus.Fields{
				"err": err,
			}).Error("error in translating")
			return
		}
		return true, false, proc, orm.FullSubProcess{}
	}

	//如果是子流程文件，添加子流程
	if _, ok := data["subprocess"]; ok {
		//将子流程解析成FullSubProcess对象
		var subproc orm.FullSubProcess
		err = json.Unmarshal(jsonData, &subproc)
		if err != nil {
			global.LOG.WithFields(logrus.Fields{
				"err": err,
			}).Error("error in translating")
			return
		}
		return false, true, orm.FullProcess{}, subproc
	}

	return

}
